<?php

namespace Agp\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Agp\CoreBundle\Entity\CobrancaContrato;
use APY\DataGridBundle\Grid\Mapping as GRID;

/**
 * Agp\CoreBundle\Entity\VendaAgape
 *
 * @ORM\Table(name="venda_agape")
 * @ORM\Entity(repositoryClass="Agp\CoreBundle\Repository\VendaAgapeRepository")
 * @ORM\HasLifecycleCallbacks
 * @GRID\Source(columns="codVendaAgape, dtVenda, empresa.razaoSocial, empresa.codEmpresa, situacao")
 */
class VendaAgape
{
    /**
     * @var integer $codVendaAgape
     *
     * @ORM\Column(name="cod_venda_agape", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @GRID\Column(title="Código", type="text", size="5", primary=true)
     */
    protected $codVendaAgape;
 
    /**
     * @ORM\ManyToOne(targetEntity="Agp\CoreBundle\Entity\Empresa", cascade={"persist"}, fetch="LAZY")
     * @ORM\JoinColumn(name="cod_empresa", referencedColumnName="cod_empresa", onDelete="restrict", nullable=false)
     * @var object
     * @Assert\NotBlank(groups={"add"})
     * @GRID\Column(field="empresa.codEmpresa", visible=false, title="Empresa", type="text")
     * @GRID\Column(field="empresa.razaoSocial", title="Empresa", type="text")
     */
    protected $empresa;
    
    /**
     * @ORM\ManyToMany(targetEntity="Agp\CoreBundle\Entity\CobrancaContrato", inversedBy="vendas", cascade={"persist"})
     * @ORM\JoinTable(name="venda_agape_cobranca_contrato",
     *     joinColumns={@ORM\JoinColumn(name="cod_venda_agape", referencedColumnName="cod_venda_agape", onDelete="restrict")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="cod_cobranca_contrato", referencedColumnName="cod_cobranca_contrato", onDelete="restrict")}
     * )
     * @var ArrayCollection $cobrancas
     */ 
    protected $cobrancas;
    
    /**
     *
     * @ORM\Column(name="dt_venda", type="datetime", nullable=false)
     * @GRID\Column(title="Data", type="datetime")
     */
    protected $dtVenda;

    /**
     * @ORM\OneToMany(targetEntity="ItemVendaAgape", mappedBy="venda", cascade={"all"}, orphanRemoval=true)
     * @var ArrayColletion
     */
    protected $itens;
    
    const SIT_ATIVO = 'ativo';
    const SIT_PAGO = 'pago';
    const SIT_CANCELADO = 'cancelado';
    /**
     * @ORM\Column(type="string", length=45, nullable=false)
     * @var string
     * 
     * @GRID\Column(title="Situação", type="text", align="center")
     */
    protected $situacao;
    
    public function __construct() {
        $this->itens = new ArrayCollection;
        $this->cobrancas = new ArrayCollection;
        $this->dtVenda = new \DateTime;
        $this->situacao = self::SIT_ATIVO;
        $this->parcela = 1;
    }
    
    // RETORNA O COD DA ÚLTIMA COBRANÇA DO TIPO venda
    public function getLastCodCobranca(){
        $cobrancas = array();
        foreach ($this->cobrancas as $cobranca){
           if ($cobranca->getTipo() == CobrancaContrato::TP_VENDA){
              $cobrancas[] = $cobranca;
           }
        }
        
        return end($cobrancas)->getCodCobrancaContrato();
    }
    
    public function getValorTotal()
    {
        $total = 0;
        foreach($this->getItens() as $item){
            $total += $item->getValorTotalItem();
        }
        
//        $valorParcela = $this->getValorTotalVenda() / $this->cobrancas->count();
//        
//        $totalParcelado = 0;
//        for ($i = 1; $i <= $this->cobrancas->count(); $i++){
//            $totalParcelado += number_format($valorParcela, 2, '.','');
//        }
//        
//        $diferenca = number_format(($this->getValorTotalVenda() - $totalParcelado), 2, '.','');
//        
//        for ($i = 1; $i <= $this->cobrancas->count(); $i++){
//            if ($i ==  $this->cobrancas->count()){
//                $parcela = $valorParcela+$diferenca;
//            }else{
//                $parcela = $valorParcela;
//            }
//            
//        }

        return $this->getValorTotalVenda();

    }
    
    public function getValorTotalVenda()
    {
        $total = 0;
        foreach($this->getItens() as $item){
            $total += $item->getValorTotalItem();
        }
        
        return $total;
    }
    
    public function getValorTotalCobrancaVenda()
    {
        return $this->getValorTotalVenda() / $this->getQtdCobrancasNotCancelado();
    }
    
    public function getValorTotalDiferenca(){
        
        
        $valorParcela = $this->getValorTotalVenda() / $this->getQtdCobrancasNotCancelado();
        //var_dump(floor($valorParcela * 100) / 100);
        $totalParcelado = 0;
        for ($i = 0; $i < $this->getQtdCobrancasNotCancelado(); $i++){
            $totalParcelado = $totalParcelado + number_format($valorParcela, 2, '.','');
        }
        
        $diferenca = number_format(($this->getValorTotalVenda() - $totalParcelado), 2, '.','');
        
        if ($diferenca < 0){
            $diferenca = 0;
        }
  
        return ($this->getValorTotalVenda() / $this->getQtdCobrancasNotCancelado()) + $diferenca;
    }
    
    public function getQtdCobrancasNotCancelado(){
        $i = 0;
        foreach ($this->cobrancas as $cobranca){
            if ($cobranca->getSituacao() != CobrancaContrato::COB_CANCELADO){
                $i += 1;
            }
        }
        
        return $i;
    }

    public function isAtivo(){
        return $this->situacao == self::SIT_ATIVO ? true : false;
    }
    
    public function isCancelado(){
        return $this->situacao == self::SIT_CANCELADO ? true : false;
    }

    public function getCodVendaAgape()
    {
        return $this->codVendaAgape;
    }

    public function getEmpresa() {
        return $this->empresa;
    }

    public function setEmpresa($empresa) {
        $this->empresa = $empresa;
    }

    public function getItens() {
        return $this->itens;
    }

    public function setItens($itens) {
        $this->itens = $itens;
    }
    
    public function addItem($item) {
        $this->itens[] = $item;
    }
    
    public function getDtVenda() {
        return $this->dtVenda;
    }

    public function setDtVenda($dtVenda) {
        $this->dtVenda = $dtVenda;
    }

    public function getSituacao() {
        return $this->situacao;
    }

    public function setSituacao($situacao) {
        $this->situacao = $situacao;
    }

    public static function getSituacaoList(){
        return array(self::SIT_ATIVO => ucfirst(self::SIT_ATIVO),
                     self::SIT_CANCELADO => ucfirst(self::SIT_CANCELADO));
    }
    
    public function getCobrancas() {
        return $this->cobrancas;
    }

    public function setCobrancas($cobrancas) {
        $this->cobrancas = $cobrancas;
    }
    
    public function addCobranca($cobranca) {
        $this->cobrancas[] = $cobranca;
    }

}
